package com.tdam2011.grupo05.ui.activities.contactos;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.provider.ContactsContract.Contacts;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;

import com.tdam2011.grupo05.R;
import com.tdam2011.grupo05.entities.contact.Contact;
import com.tdam2011.grupo05.ui.activities.contactos.ContactosFragment.ListaContactosListener;

public class ContactoActivity extends FragmentActivity implements
		ListaContactosListener {

	private static final String ORDEN_ALFA = "ordenAlfa";

	private static final String condition = "((" + Contacts.DISPLAY_NAME
			+ " NOTNULL) AND (" + Contacts.HAS_PHONE_NUMBER + "=1) AND ("
			+ Contacts.DISPLAY_NAME + " LIKE '%";
	private static final String ORDER_BY_DESC = Contacts.DISPLAY_NAME
			+ " COLLATE LOCALIZED DESC";
	private static final String ORDER_BY_ASC = Contacts.DISPLAY_NAME
			+ " COLLATE LOCALIZED ASC";
	private final int DIALOG_ORDENAR = 1;
	private static final int ASC = 0;
	SharedPreferences settingOrden;
	SharedPreferences.Editor prefEditor;

	private final Handler mHandler = new Handler();
	private final ExecutorService mExecutor = Executors.newCachedThreadPool();
	private ContactosFragment contactFragment;

	private FragmentManager manager;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.activity_contacto);
		settingOrden = getPreferences(MODE_PRIVATE);
		// //////////////INICIALIZACION BOTON
		// ORDENAMIENTO/////////////////////////
		ImageView ordenar = (ImageView) findViewById(R.id.ordenar_titulo);
		ordenar.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				onCreateDialog(DIALOG_ORDENAR);
			}
		});

		// chequeo que la actividad esta usando el layout, por eso le debo
		// poner el primer fragment
		if (findViewById(R.id.fragment_contenier) != null) {

			contactFragment = new ContactosFragment();
			Bundle bundle = new Bundle();

			int order = settingOrden.getInt(ORDEN_ALFA, 0);
			if (order == ASC) {
				bundle.putString(ContactosFragment.ORDER_BY, ORDER_BY_ASC);
			} else {
				bundle.putString(ContactosFragment.ORDER_BY, ORDER_BY_DESC);
			}

			String filterPref = settingOrden.getString("filterString", null);
			if (filterPref != null)
				bundle.putString(ContactosFragment.SELECTION, condition
						+ filterPref + "%' ))");

			contactFragment.setArguments(bundle);
			manager = getSupportFragmentManager();
			manager.beginTransaction()
					.add(R.id.fragment_contenier, contactFragment).commit();

		}
	}

	@Override
	public void onChangeOrderListener() {
		// TODO Auto-generated method stub

	}

	@Override
	public void onClickContactListener(final Contact contact) {
		Runnable r = new Runnable() {

			@Override
			public void run() {
				mHandler.post(new Runnable() {

					@Override
					public void run() {
						FragmentTransaction t = manager.beginTransaction();
						ContactoDetailFragment contacto = new ContactoDetailFragment();
						contacto.setContacto(contact);
						t.setCustomAnimations(android.R.anim.slide_in_left,
								android.R.anim.slide_out_right);
						t.replace(R.id.fragment_contenier, contacto, null);
						t.addToBackStack(null);
						t.commit();
					}
				});
			}
		};
		mExecutor.submit(r);

	}

	protected Dialog onCreateDialog(int id) {

		switch (id) {
		case DIALOG_ORDENAR:
			final CharSequence[] items = getResources().getStringArray(
					R.array.filter_contact);
			return new AlertDialog.Builder(ContactoActivity.this)
					.setTitle(R.string.text_dialog_ordenar)
					.setSingleChoiceItems(items,
							settingOrden.getInt(ORDEN_ALFA, 0),
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int whichButton) {
									prefEditor = settingOrden.edit();
									if (whichButton == 0) {

										refreshListContact(ORDER_BY_ASC);
										prefEditor.putInt(ORDEN_ALFA, 0);
										prefEditor.commit();
									} else {

										refreshListContact(ORDER_BY_DESC);
										prefEditor.putInt(ORDEN_ALFA, 1);
										prefEditor.commit();
									}
									dialog.dismiss();
								}
							}).show();
		}
		return null;
	}

	public void refreshListContact(String orderBy) {
		if (contactFragment.isVisible()) {
			Bundle bundle = new Bundle();
			bundle.putString(ContactosFragment.ORDER_BY, orderBy);
			contactFragment.getLoaderManager().destroyLoader(0);
			contactFragment.getLoaderManager().initLoader(0, bundle,
					contactFragment);
		}
	}

	public void onFilterChange(String orderBy) {
	}

}
